<?php
/* ###############################################################################
 *
 * $Id: form.php 46 2014-10-13 15:00:00Z expertsoftware.i@gmail.com $
 *
 * システム名
 *   PHP Web フレームワーク [Ponzu]
 *
 * 機能
 *   フォーム ライブラリ
 *
 * バージョン
 *   0.0.0_0
 *
 * ライセンス
 *   LGPL v2.0
 *
 * 履歴
 *   2007/07/01 K.Sonohara
 *     新規作成。
 *
 * ###############################################################################*/

/**
 * 引数安全取得
 * @access public
 * @param value 値
 * @return 処理結果
 */
function inputValue($value, $file=false) {
  //長すぎる場合無視
  if (strlen($value) > 1024) {
    return "";
  }

  //特定の文字を削除
  $ret = strip_tags($value);
  $ret = str_replace(";","", $ret);
  $ret = str_replace("\\","", $ret);
  $ret = str_replace("\"","", $ret);
  $ret = str_replace("'","", $ret);
  $ret = str_replace("$","", $ret);
  $ret = str_replace("&","", $ret);
  $ret = str_replace("%","", $ret);

  if ($file) {
    $ret = str_replace("/","", $ret);
    $ret = str_replace("..","", $ret);
  }

  return $ret;
}

function FORM_HTML() {
    global $scripts;

    if (!defined('PAGE_JSONED')) {
      define("PAGE_JSONED", "./" . PAGE_ID . ".php");
    }
    $scripts[] = bootstrapForm(PAGE_TITLE, "json_form", PAGE_JSON, PAGE_JSONED, PAGE_CONFIRM);
}

function htmlFormJson($level=null, $id=null, $confirm=true, $json=null, $post="PAGE_POST") {
  // 定義値
  if (!defined('PAGE_LEVEL'))
    define("PAGE_LEVEL", $level);
  if (!defined('PAGE_ID'))
    define("PAGE_ID",    $id);
  if (!defined('PAGE_TITLE')) {
    global $main_menus;
    define("PAGE_TITLE",  $main_menus->menus[PAGE_LEVEL]->menus[PAGE_ID]->title);
  }
  if (!defined('PAGE_CAPTION'))
    define("PAGE_CAPTION", false);
  define("PAGE_SIDE", true);
  define("PAGE_HTML", "FORM_HTML");
  if (!defined('PAGE_JSON')) {
    if ($json != null) {
      define("PAGE_JSON", $json);
    } else {
      define("PAGE_JSON", $_SERVER["SCRIPT_NAME"] . "?m=1");
    }
  }
  if (!defined('PAGE_JSONED')) {
    if ($json != null) {
      define("PAGE_JSONED", "./" . PAGE_ID . ".php");
    } else {
      define("PAGE_JSONED", $_SERVER["SCRIPT_NAME"]);
    }
  }
  define("PAGE_CONFIRM", $confirm);

  // 変数

  //処理
  if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $result = array();
    $result['status'] = 1;
    $result['message'] = "";

    try {
      $values = valuesFormPostJSON(JSON_FILE);

      $result = call_user_func($post, $values);
    } catch(Exception $e) {
      $result['message'] = $e;
    }

    echo stringToJson($result);
  } else {
    $mode = 0;
    if (isset($_REQUEST["m"])) {
      $mode = $_REQUEST["m"];
    }

    // HTML表示
    if ($mode == 0) {
      //SXB共通
      doHTML();
    // JSON表示
    } else if ($mode == 1) {
      try{
        $json =loadJsonFile(JSON_FILE);

        if (defined("PAGE_VALUE")) {
          call_user_func(PAGE_VALUE, $json);
        }

        echo stringFromJson($json);
      } catch(Exception $e) {
      }
    }
  }
}


function formHTML($level=null, $id=null, $confirm=true, $json=null, $post="PAGE_POST") {
  global $main_menus;

  if (!defined('PAGE_LEVEL'))
    define("PAGE_LEVEL", $level);
  if (!defined('PAGE_ID'))
    define("PAGE_ID",    $id);

  $l = PAGE_LEVEL . '/';
  if (PAGE_LEVEL == "-") $l = "";

  if (!defined('PAGE_TITLE'))
  	define("PAGE_TITLE",  $main_menus->menus[PAGE_LEVEL]->menus[PAGE_ID]->title);
//	define("PAGE_DESCRIPTION",  $sxb->getDescription());
//	define("PAGE_KEYWORS",  $sxb->getKeywords());

  if (!defined('PAGE_CAPTION'))
    define("PAGE_CAPTION", true);
  define("PAGE_SIDE", true);
  define("PAGE_HTML", "FORM_HTML");
  if (!defined('PAGE_JSON')) {
    if ($json != null) {
      define("PAGE_JSON", $json);
    } else {
      define("PAGE_JSON", "./" . PAGE_ID . ".json");
    }
  }
  define("PAGE_CONFIRM", $confirm);

  if ($_SERVER["REQUEST_METHOD"] != "POST") {
    doHTML();
  } else {
    include_once BASE_INC."module/3rd/json.php";

    $cjson = new Services_JSON();

    $result = array();
    $result['status'] = 1;
    $result['message'] = "";
    try {
      $values = valuesFormPostJSON(PAGE_JSON);

      $result = call_user_func($post, $values);
    } catch(Exception $e) {
      $result['message'] = $e;
    }

    echo $cjson->encode($result);
  }
}

function valuesFormPostJSON($file_json) {
  include_once BASE_INC."module/3rd/json.php";

  $cjson = new Services_JSON();

  $file = loadTextFile($file_json);

  $json_form = $cjson->decode($file)->items;

  $values = array();
  foreach ($json_form as $value) {
    try {
      if (isset($_POST)) {
        if (isset($_POST[$value->name])) {
          $value->value = $_POST[$value->name];
        }
      }
    } catch (Exception $e){ 
    }
    $values[$value->name] = $value;
  }

  return $values;
}

function isValueJson($value) {
  if ($value->type == "iframe") {
    return false;
  }

  return true;
}

function sqlCreateJsonSQLite($db, $values) {
  $create = sprintf(
    "CREATE TABLE IF NOT EXISTS %s (",
    DB_TABLE
  );
  $first = true;
  foreach ($values as $value) {
    if (!isValueJson($value)) continue;

    if ($first) {
      $first = false;
    } else {
      $create .= ",";
    }

    $create .= "a_" . $value->name . " TEXT";
    if ($value->name == DB_KEY) {
      $create .= " PRIMARY KEY";
    }
  }
  $create .= ")";
  return $create;
}

function sqlCountJsonSQLite($db, $values) {
  $select = sprintf(
    "SELECT count(*) FROM %s WHERE a_%s = '%s'",
    DB_TABLE,
    DB_KEY,
    $db->escapeString($values[DB_KEY]->value)
  );
  return $select;
}

function sqlInsertJsonSQLite($db, $values) {
  $insert = sprintf(
    "INSERT INTO %s(",
    DB_TABLE
  );
  $first = true;
  foreach ($values as $value) {
    if (!isValueJson($value)) continue;

    if ($first) {
      $first = false;
    } else {
      $insert .= ",";
    }
    $insert .= "a_" . $value->name;
  }
  $insert .= ") VALUES(";
  $first = true;
  foreach ($values as $value) {
    if (!isValueJson($value)) continue;

    if ($first) {
      $first = false;
    } else {
      $insert .= ",";
    }
    $insert .= "'" . $db->escapeString($value->value) . "'";
  }
  $insert .= ")";

  return $insert;
}

function sqlUpdateJsonSQLite($db, $values) {
  $update = sprintf(
    "UPDATE %s SET ",
    DB_TABLE
  );
  $first = true;
  foreach ($values as $value) {
    if (!isValueJson($value)) continue;

    if ($first) {
      $first = false;
    } else {
      $update .= ", ";
    }
    $update .= "a_" . $value->name . " = '" . $db->escapeString($value->value) . "'";
  }
  $update .= " WHERE a_" . DB_KEY . " = '" . $db->escapeString($values[DB_KEY]->value) . "'";

  return $update;
}

function saveJsonSQLite($db_file, $values, $override) {
  $db = new SQLite3($db_file);

  $create = sqlCreateJsonSQLite($db, $values);
  $count = sqlCountJsonSQLite($db, $values);

  $result = array();
  $result['status'] = 1;
  $result['message'] = "エラーが発生しました。";
  try {
    $db->query($create);
    $r = $db->query($count);

    if ($r) {
      $row = $r->fetchArray();
      if ($row[0] == 0) {
        $insert = sqlInsertJsonSQLite($db, $values);
        $r = $db->query($insert);
        if ($r) {
          $result['status'] = 0;
          $result['message'] = "";
        }
      } else if ($override) {
        $update = sqlUpdateJsonSQLite($db, $values);
        $r = $db->query($update);
        if ($r) {
          $result['status'] = 0;
          $result['message'] = "";
        }
      } else {
        $result['status'] = 2;
        $result['message'] = "既に登録済です。";
      }
    }
  } catch(Exception $e) {
  }
  try {
    if ($db) $db->close();
  } catch(Exception $e) {
    //
  }

  return $result;
}

function mailFormPostJSON($template, $title, $values, $mail_from=SITE_FROMMAIL, $mail_to, $mail_cc=null, $mail_bcc=SITE_MAIL) {
  $vs = array();
  foreach ($values as $k => $v) {
    if ($v->value) {
      $vs[$k] = $v->value;
    } else {
      $vs[$k] = "";
    }
  }

  return sendMail(
    $mail_from,
    null,
    $mail_to,
    null,
    $mail_cc,
    null,
    $mail_bcc,
    null,
    $title,
    templateMail($template, $vs)
  );
}
?>
